layui.use(['layer','form','table'], function() {
    var layer = layui.layer, form = layui.form,table = layui.table;
    $('.sel-load').selLoad(function () {
        form.render('select');

        form.on('radio(overseasTakeInfoId)',function () {
            let customerOverseasDeliveryId = $('input[name="overseasTakeInfoId"]:checked').val();
            showDeliveryInfo(customerOverseasDeliveryId);
        });

        var id = getUrlParam('id');
        if(isNotEmpty(id)){
            obtainDetail(id);
        }else{
            //生成单号
            generateDocNo();
            $('#deliveryDate').val(getNowFormatTime());
            fullMember([]);
        }
    });

    $(".close-window").click(function () {
        parent.reloadList();
        closeThisWin();
    });
});
function obtainDetail(id){
    show_loading();
    $.get('/scm/overseasDeliveryNote/detail',{id:id},function (res){
        if(isSuccessWarnClose(res)){
            layui.form.val('mainForm',res.data.overseasDeliveryNote);
            //禁用客户重新选择
            $(".auto-customer").attr("readonly","readonly");
            $(".auto-customer").removeAttr("clear-val");
            //获取境外送货信息
            takeInformation(res.data.overseasDeliveryNote.customerName,res.data.overseasDeliveryNote.consigneeId);
            fullMember(res.data.members);
        }
    });
}
function selectAndSaveDeliveryNoteMembers(isOpen){
    if(!checkedForm($('#mainForm'))){return;}
    var params = $('#mainForm').serializeJson();
    postJSON('scm/overseasDeliveryNote/saveMain',params,function (res){
        $('#id').val(res.data);
        if(isOpen) {
            var params = $('#mainForm').serializeJson();
            openwin('/logistics/overseasDeliveryNote/deliveryMembers.html?overseasDeliveryNoteId='+$('#id').val()+'&customerId='+params.customerId,'派送订单明细选择',{area: ['1400px', '800px']});
        } else {
            show_success("保存成功，您可以选择需要派送的订单明细");
        }
    });
}
function generateDocNo() {
    show_loading();
    $.post(rurl('scm/serialNumber/generateDocNo'),{'type':'overseas_delivery_note'},function (res) {
        if(isSuccess(res)){
            $('#docNo').val(res.data);
        }
    });
}
function fullCustomerData(data) {
    $('#customerId').val(data.id);
    clearDeliveryInfo();//清空收货信息
    takeInformation(data.name);//获取境外交货送货信息
}

function fullMember(members){
    layui.table.render({
        elem: '#deliveryMemberTable',limit:5000,height:'full-340',totalRow: true,page:false,text: {
        none: '<a href="javascript:" class="def-a" onclick="selectAndSaveDeliveryNoteMembers(true)"><i class="layui-icon layui-icon-ok"></i>点击选择派送明细</a>'
    }
        ,cols: [[
            {type: 'checkbox', fixed: 'left'},
            {type:'numbers',title:'序号',width:45}
            ,{field:'expOrderNo',title:'订单号',width:120,totalRowText: '合计'}
            ,{field:'model',title:'型号',width:200}
            ,{field:'brand',title:'品牌',width:120}
            ,{field:'name',title:'名称',width:120}
            ,{field:'quantity',title:'派送数量',width:90,align:'right',totalRow: true}
            ,{field:'cartonNum',title:'派送件数',width:90,align:'right',totalRow: true}
            ,{field:'grossWeight',title:'毛重',width:90,align:'right',totalRow: true,totalRowType:'num4'}
            ,{field:'netWeight',title:'净重',width:90,align:'right',totalRow: true,totalRowType:'num4'}
            ,{field:'unitName',title:'单位',width:50,align:'center'}
        ]]
        , data: members
    });
    formatTableData();
}
function clearDeliveryInfo() {
    layui.form.val('mainForm',{
        'consignee':'',
        'consigneeLinkMan':'',
        'consigneeLinkTel':'',
        'consigneeAddress': ''
    });
}
//获取境外送货地址
function takeInformation(name,defVal){
    var customerName = (name || $('#customerName').val());
    if(!isEmpty(customerName)){
        var takeInformationsObj = $('#takeInformations');
        takeInformationsObj.html('<img src="'+rurl('images/indicator.gif')+'"/>');
        $.post(rurl('scm/customerAbroadDeliveryInfo/effectiveList'),{'customerName':customerName},function (res) {
            var thtml = [];
            $.each((res.data || []),function (i,o) {
                if(isEmpty(defVal)){defVal = o.id;}
                thtml.push('<div class="range-list-item"><input type="radio"  lay-filter="overseasTakeInfoId" name="overseasTakeInfoId" value="'+o.id+'" title="【'+o.companyName+'】'+o.provinceName+o.cityName+o.areaName+o.address+' ('+o.linkPerson+' '+o.linkTel+')" '+(o.id==defVal?'checked="true"':'')+'></div>');
            });
            takeInformationsObj.html(thtml.join(""));
            layui.form.render('radio');

            //展示详细的收货信息
            if(isNotEmpty(defVal)) {
                showDeliveryInfo(defVal);
            }
        });
    }else{
        show_error('请先选择客户');
    }
}

function showDeliveryInfo(id) {
    $.get('/scm/customerAbroadDeliveryInfo/detail',{id:id},function (res){
        if(isSuccess(res)){
            var o = res.data
            layui.form.val('mainForm',{
                'consignee':o.companyName,
                'consigneeLinkMan':o.linkPerson,
                'consigneeLinkTel':o.linkTel,
                'consigneeAddress': o.provinceName+o.cityName+o.areaName+o.address
            });
        }
    });
}

// 境外送货信息
$('#maintainInformation').click(function () {
    var customerName = $('#customerName').val();
    var customerId = $("#customerId").val();
    if(!isEmpty(customerName)){
        var mid=parent.parent.obtainMIdByOperation('customer_list'),taskArg={"documentId":customerId,"documentClass":"","operation":"customer_edit"};
        if(isEmpty(mid)){prompt_warn('对不起您无此权限,请联系贵司管理员授权!');return;}
        setLocalStorage('TASK_'+mid,JSON.stringify({"name":customerName}));
        setLocalStorage('AUTO_TASK',JSON.stringify(taskArg));
        parent.parent.refreshTab(mid);
    }else{
        show_error('请先选择客户');
    }
});

function deleteMembers() {
    var id = $("#id").val();
    if(isEmpty(id)) {
        show_error("请先保存境外派送单主单数据");
        return;
    }
    var data = layui.table.checkStatus('deliveryMemberTable').data;
    if(data.length==0){
        show_error('请勾选需要删除的待派送订单明细');
        return;
    }
    var ids = [];
    for(var i=0;i<data.length;i++){
        ids.push(data[i].id);
    }
    $.post(rurl('/scm/overseasDeliveryNote/removeIds'),{
        overseasDeliveryId:id,
        ids:ids.join(","),
    },function (res){
        show_success('删除成功');
        obtainDetail(id);
    });
}